import { defineStore } from 'pinia';
import { Message } from '@arco-design/web-vue';
import { getUserTeamsInPrj } from '@/api/project';
import { PrjPermissionState } from './types';

const usePrjPermissionStore = defineStore('prjPermission', {
  state: (): PrjPermissionState => ({
    id: '',
    userId: '',
    name: '',
    projectAdmin: 0,
    teamList: [],
  }),

  getters: {
    isPrjAdmin(state: PrjPermissionState) {
      return !!state.projectAdmin;
    },
  },

  actions: {
    // Reset user's information
    resetInfo() {
      this.$reset();
    },

    // Set permission list
    async setPermission(projectId: string) {
      try {
        const res = await getUserTeamsInPrj(projectId);
        if (res.status && res.data?.[0]) {
          this.$patch(res.data[0]);
        } else {
          this.$reset();
        }
      } catch (err) {
        if (typeof err === 'string') {
          Message.error(err);
        }
      }
    },
  },
});

export default usePrjPermissionStore;
